package online.listener;

import java.io.Serializable;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * Mutexリスナ
 *
 * @author Tadashi Nakayama
 */
public final class SessionMutexListener implements HttpSessionListener {

	/** クラス名 */
	private static final String CLAZZ = SessionMutexListener.class.getName();

	/**
	 * @see javax.servlet.http.HttpSessionListener
	 * #sessionCreated(javax.servlet.http.HttpSessionEvent)
	 */
	@Override
	public void sessionCreated(final HttpSessionEvent se) {
		se.getSession().setAttribute(CLAZZ, new Mutex());
	}

	/**
	 * @see javax.servlet.http.HttpSessionListener
	 * #sessionDestroyed(javax.servlet.http.HttpSessionEvent)
	 */
	@Override
	public void sessionDestroyed(final HttpSessionEvent se) {
		se.getSession().removeAttribute(CLAZZ);
	}

	/**
	 * Mutex取得
	 *
	 * @param session セション
	 * @return Mutexオブジェクト
	 */
	public static Object getMutex(final HttpSession session) {
		Object ret = session.getAttribute(CLAZZ);
		return ret != null ? ret : session;
	}

	/**
	 * Mutex
	 *
	 * @author Tadashi Nakayama
	 */
	private static final class Mutex implements Serializable {
		/** serialVersionUID */
		private static final long serialVersionUID = 494974690896138342L;

		/**
		 * コンストラクタ
		 */
		public Mutex() {
			super();
		}
	}
}
